<?php

class SeoSettings extends CActiveRecord
{
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return '{{seo_settings}}';
	}

	public function rules()
	{
		return array(
			array('pageId, description, keywords', 'required'),
			array('pageId', 'length', 'max'=>255),
			array('defaultId', 'length', 'max'=>1),
			array('id, pageId, description, keywords, defaultId', 'safe', 'on'=>'search'),
		);
	}

	public function relations()
	{
		return array(
		);
	}

	public function attributeLabels()
	{
		return array(
			'id' => tt('ID'),
			'pageId' => tt('Page'),
			'description' => tt('Description'),
			'keywords' => tt('Keywords'),
			'defaultId' => tt('Default'),
		);
	}

	public function search()
	{
		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('pageId',$this->pageId,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('keywords',$this->keywords,true);
		$criteria->compare('defaultId',$this->defaultId);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'pagination'=>array(
				'pageSize'=>param('adminPaginationPageSize', 20),
			),
		));
	}
	
	public function generateDefaultPageId($controller)
	{
		return str_replace('/','-',$controller->getUniqueId()).'-'.$controller->getAction()->id.'-'.Yii::app()->language;
	}
	
	public function generatePageId($controller)
	{
		$defaultPageId = $this->generateDefaultPageId($controller);
		if (!empty($controller->pageIdKey))
		{
			$params = $controller->getActionParams();

			$pageIdKey = explode('|', $controller->pageIdKey);
			foreach ($pageIdKey as $key)
			{
				if (isset($params[$key]))
				{
					$pageId = $defaultPageId.'-'.$params[$key];
					return $pageId;
				}
			}
		}
		return false;
	}
	
	public function getPageSettings($pageId)
	{
		if (!$pageId)
			return false;
		
		$sql = "SELECT keywords, description FROM ".$this->tableName()." WHERE (pageId IN (:pageid))";
		$command = Yii::app()->db->createCommand($sql);
		
		$command->bindParam(':pageid', $pageId);
		$result = $command->queryRow();
		
		return $result;
	}
	
	public function getDefaultSettings() 
	{
		$sql = "SELECT * FROM ".$this->tableName()." WHERE defaultId=:defaultid";
		$command = Yii::app()->db->createCommand($sql);
		
		$command->bindValue(':defaultid', '1');
		$result = $command->queryAll();
		
		return $result;
	}

	public function save()
	{
		if ($this->exists("pageId=?", array($this->attributes['pageId'])))
		{
			$sql = "UPDATE ".$this->tableName()." SET description=:description, keywords=:keywords WHERE pageId=:pageid";
			$command = Yii::app()->db->createCommand($sql);
			
			$command->bindParam(':description', $this->attributes['description']);
			$command->bindParam(':keywords', $this->attributes['keywords']);
			$command->bindParam(':pageid', $this->attributes['pageId']);
			
			return $command->execute();
		}
		return parent::save();
	}
}